<template>
  <!-- 订单列表 -->
  <div>
    <!-- 模糊搜索 -->
    <el-card style="height: 50px" :body-style="{ padding: '10px', height: '50px', width: '100%'}">
      <div class="box-card-div">
        <el-form :inline="true" :model="courseDTO" ref="courseDTOForm" class="demo-form-inline">
          <!-- 课程号 -->
          <el-form-item label="课程号" prop="id">
            <el-input size="small" v-model="courseDTO.id" placeholder="请输入课程号"></el-input>
          </el-form-item>
          <!-- 课程名称 -->
          <el-form-item label="课程名称" prop="name">
            <el-input size="small" v-model="courseDTO.name" placeholder="请输入课程名称"></el-input>
          </el-form-item>
          <!-- 授课教师 -->
          <el-form-item label="授课教师" prop="teacher">
            <el-input size="small" v-model="courseDTO.teacher" placeholder="请输入授课老师的名字"></el-input>
          </el-form-item>

          <!-- 确定和取消按钮 -->
          <el-form-item>
            <el-button type="success" round size="small" @click="findAll" icon="el-icon-search">查询</el-button>
            <el-button type="warning" round size="small" @click="resetCourseForm('courseDTOForm')"
                       icon="el-icon-refresh-left">重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 添加和批量删除按钮 -->
    <div class="button-container">
      <el-button class="btn_add" type="primary" @click="handleAddCourse" size="middle" icon="el-icon-plus">新增
      </el-button>
      <el-button class="btb_del" type="danger" @click="deleteCourseByBatch" size="middle" icon="el-icon-delete">
        批量删除
      </el-button>
      <el-button class="btb_del" type="primary" @click="uploadExcelDialog = true" size="middle" icon="el-icon-delete">
        导入
      </el-button>
      <el-button class="btb_del" type="warning" @click="exportCourse" size="middle" icon="el-icon-delete">导出
      </el-button>
    </div>

    <!-- 实现修改和新增对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="editDialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="courseForm" :model="courseList" :rules="rules" label-width="100px">
        <!-- 课程编号 -->
        <el-form-item label="课程编号" prop="id">
          <el-input v-model="courseList.id" disabled></el-input>
        </el-form-item>
        <!-- 课程名称 -->
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseList.name"></el-input>
        </el-form-item>
        <!-- 授课教师 -->
        <el-form-item label="授课教师" prop="teacher">
          <el-input v-model.number="courseList.teacher"></el-input>
        </el-form-item>
        <!-- 教室容量 -->
        <el-form-item label="教室容量" prop="size">
          <el-input v-model.number="courseList.size"></el-input>
        </el-form-item>
      </el-form>
      <!-- 取消和确定按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetCourseForm('courseForm')">取 消</el-button>
        <el-button type="primary" @click="saveCourse('courseForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!--导入文件对话框 -->
    <el-dialog
      title="导入本地课程文件"
      width="26%"
      :visible.sync="uploadExcelDialog"
      :close-on-click-modal="false"
    >
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="importCourse"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>
        <el-button type="primary" @click="">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 课程表格数据 -->
    <el-card class="order-list">
      <el-table
        :data="tableData"
        border
        class="order-table"
        style="width: 100%; font-size: 20px"
        height="500"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 做出复选框 -->
        <el-table-column type="selection" width="55px"></el-table-column>
        <!-- 课程编号 -->
        <el-table-column prop="id" label="课程编号" width="150px"></el-table-column>
        <!-- 课程名称 -->
        <el-table-column prop="name" label="课程名称" width="150px"></el-table-column>
        <!-- 教师名称 -->
        <el-table-column prop="teacher" label="教师名称" width="150px"></el-table-column>
        <!-- 教室容量 -->
        <el-table-column prop="size" label="教室容量" width="150px"></el-table-column>
        <!-- 当前选课人数 -->
        <el-table-column prop="courseNum" label="当前选课人数" width="150px">
          <!-- 如果当前选课人数为null，则显示为0 -->
          <template slot-scope="scope">
            <span v-if="scope.row.courseNum != null">{{ scope.row.courseNum }}</span>
            <span v-if="scope.row.courseNum == null">0</span>
          </template>
        </el-table-column>

        <!-- 展示操作按钮 -->
        <el-table-column label="操作" width="350px">
          <template slot-scope="scope">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="handleCourseEdit(scope.$index, scope.row)"
              style="margin-right: 5px; margin-bottom: 2px"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleCourseDeleteById(scope.$index, scope.row)"
              style="margin-bottom: 2px"
            >
              删除
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"

              @click="handleCourseManage(scope.$index, scope.row)"
              style="margin-bottom: 2px; width: 150px; font-size:1px"
            >
              管理当前选课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 分页导航 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="pageSizes"
            :page-size="courseDTO.pageSize"
            :current-page="courseDTO.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
          <!-- 添加一个跳转按钮 -->
          <el-button style="margin-right: 10px" size="small" type="primary" @click="toPage">跳转</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>

<script>
import {
  addCourse,
  deleteCourseBatch,
  deleteCourseById,
  importCourse,
  queryCourseByPage,
  updateCourse
} from '@/api/course'
import path from 'path'

export default {
  name: 'CourseManager',
  data() {
    return {
      title: '添加课程',
      tableData: [],   // 表格数据
      uploadExcelDialog: false, // 上传文件对话框是否显示
      file: null,
      fileList: [],
      // 用户分页查询和模糊查询
      courseDTO: {
        pageNum: 1,
        pageSize: 3,
        // 课程号
        id: null,
        // 课程名称
        name: null,
        // 教师名称
        teacher: null
      },  // 用户分页
      total: 0, // 总条数
      courseList: {
        id: 0,
        name: '',
        teacher: '',
        size: 0
      },  // 用于添加、修改课程对话框中的数据
      pageSizes: [3, 5, 10, 20], // 分页尺寸
      editDialogVisible: false, // 编辑对话框是否显示也用于添加对话框
      multipleSelection: [], // 用于批量删除订单的复选框
      rules: {
        id: [{ required: true, message: '请输入课程编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        teacher: [{ required: true, message: '请输入教师名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 上传前的回调，用于清空上次上传的文件列表
    beforeUpload(file) {
      console.log('开始上传，清空上次的文件列表')
      this.fileList = [] // 清空文件列表
      return true
    },
    // 导入文件
    importCourse() {
      const file = this.file
      // FormData是js对象,用于存储表单数据
      const formData = new FormData()
      formData.append('file', file) // 由后端接口决定,后端参数叫file
      // 封装的上传文件方法
      importCourse(formData).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          // 上传成功后添加到文件列表
          this.fileList.push({
            name: file.name
          }) // 上传成功后添加到文件列表
          this.uploadExcelDialog = false // 关闭弹窗
          this.pageNum = 1 // 刷新列表
          this.clearImportList() // 刷新列表
          // 重新查询
          this.findAll()
        }
      })
    },
    clearImportList() {
      // 刷新文件列表
      this.fileList = []
    },
    // 导出课程文件
    exportCourse() {
      this.$confirm('是否要下载课程文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href = 'http://localhost:9090/course/downLoadCourseExcel'
        this.$message({
          type: 'success',
          message: '导出成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },
    // 监听文件改变
    handleChange(file) {
      console.log('file', file)
      this.file = file.raw
    },

    // 模糊查询+分页处理
    findAll() {
      queryCourseByPage(this.courseDTO).then(res => {
        // 返回成功
        this.tableData = res.data.dataList
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    // 分页的两个绑定事件
    handleSizeChange(size) {
      this.courseDTO.pageSize = size
      this.findAll()
    },
    handleCurrentChange(currentPage) {
      this.courseDTO.pageNum = currentPage
      this.findAll()
    },
    // 跳转到指定页
    toPage() {
      this.findAll()
    },
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },

    // 通过订单id删除订单
    handleCourseDeleteById(index, row) {
      // 首先要进行弹框提示
      this.$confirm('是否确认删除课程编号为' + '"' + row.id + '"' + '的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const courseId = row.id
        deleteCourseById(courseId).then((ret) => {
          if (ret.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.courseDTO.pageNum = 1
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 管理当前选课
    handleCourseManage(index, row) {
      // 跳转到当前课程管理页面
      this.$router.push({ path: '/courseManager/module/currentSelCourse', query: { courseId: row.id }})
    },
    // 批量删除订单
    deleteCourseByBatch() {
      this.$confirm('是否确认删除选中的' + this.multipleSelection.length + '条数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCourseBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.courseDTO.pageNum = 1
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = []
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 点击修改按钮，触发修改对话框
    async handleCourseEdit(index, row) {
      this.title = '修改课程'
      this.editDialogVisible = true
      // 等待对话框完全打开
      this.$nextTick(() => {
        // 先重置表单（这会清除所有校验状态）
        this.$refs.courseForm.resetFields()
        // 清除校验状态
        this.$refs.courseForm.clearValidate()
        // 深拷贝数据
        this.courseList = JSON.parse(JSON.stringify(row))
        this.courseList.name = row.courseList.name
        // 转换日期格式为 Date 对象
        this.convertToDatePickerFormat(this.courseList)
      })
    },
    resetFields() {
      this.$refs.courseForm.resetFields()
    },
    // 添加一个专门处理日期字段的方法
    convertDateFields() {
      const dateFields = ['payTime', 'deliveryTime', 'receiveTime']
      dateFields.forEach(field => {
        if (this.courseList[field]) {
          this.courseList[field] = new Date(this.courseList[field])
        }
      })
    },
    // 点击新增按钮，触发新增对话框
    handleAddCourse() {
      this.title = '添加课程'
      this.courseForm = {
        payTime: '',
        deliveryTime: '',
        receiveTime: ''
      }
      this.editDialogVisible = true
      this.$refs.courseForm.resetFields() // 重置表单校验状态
    },
    // 格式化日期字段为后端预期的格式
    convertToDatePickerFormat(course) {
      const dateFields = ['payTime', 'deliveryTime', 'receiveTime']
      dateFields.forEach(field => {
        if (course[field] && typeof course[field] === 'string') {
          course[field] = new Date(course[field])
        }
      })
    },
    formatDateFields() {
      const dateFields = ['payTime', 'deliveryTime', 'receiveTime']
      dateFields.forEach(field => {
        if (this.courseList[field] instanceof Date) {
          this.courseList[field] = this.$moment(this.courseList[field]).format('yyyy-MM-dd')
        }
      })
    },

    // 点击保存按钮，触发保存事件
    saveCourse(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 格式化日期字段
          this.formatDateFields()

          if (this.title === '添加课程') {
            addCourse(this.courseList).then(ret => {
              if (ret.code === 200) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false
                this.courseDTO.pageNum = 1
                this.findAll()
                this.resetCourseForm('courseForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
          } else {
            updateCourse(this.courseList).then(ret => {
              console.log('courseList:', this.courseList)
              if (ret.code === 200) {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                  duration: 1000
                })
                this.editDialogVisible = false
                this.courseDTO.pageNum = 1
                this.findAll()
                this.resetCourseForm('courseForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetCourseForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields() // 重置表单校验状态
      })
    }
  },
  created() {
    this.findAll()
  }
}
</script>

<style scoped>
/* 表格整体样式 */
.el-table {
  margin-bottom: 20px;
  font-size: 13px;
  border: 1px solid #ebeef5;
}

/* 表头样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
  text-align: center;
  white-space: nowrap;
}

/* 单元格样式 */
.el-table td {
  text-align: center;
  padding: 10px 0;
  border-color: #ebeef5;
}

/* 操作按钮的间距调整 */
button.el-button {
  margin: 2px;
  width: 80px; /* 固定按钮宽度 */
}

.pagination-container {
  align-items: center;
  justify-content: center; /* 居中 */
  display: flex; /* 使其成为一个flex容器 */
  margin-top: 10px;
}

.button-container {
  display: flex;
  margin-left: 30px;
  width: 100px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  margin-top: 20px;
}

.button-container .btn_add {
  margin-right: 10px;
  text-align: center;
  font-size: 16px;
  width: 100px;
  border-top-left-radius: 5px;
}

.button-container .btb_del {
  margin-right: 10px;
  text-align: center;
  font-size: 14px;
  width: 150px;
  border-top-left-radius: 5px;
}

.order-list {
  padding: 0;
}

.order-table {
  margin-top: 20px;
}
</style>

